package com.Servlet;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Servlet.Dao.usersEntity;

@WebServlet("/bookInsertServlet")
public class bookInsertServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String URL = "images/2.jpg";
	static boolean isValidDate(String str) {
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		try{
			Date date = (Date)formatter.parse(str);
			return str.equals(formatter.format(date));
		}catch(Exception e){
			return false;
		}
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("utf-8");
		response.setCharacterEncoding("utf-8");
		String[] values = request.getParameterValues("bookInfo");
		String userSno = request.getParameter("userSno");
		request.setAttribute("checkFlag", "F");
		request.setAttribute("userSno", userSno);
		request.setAttribute("flag", "bookInsert");
		String check = "true";
		try {
			ArrayList<Object> al = new ArrayList<>();
			for(int i = 0; i < values.length; i++) {
				switch(i) {
					case 0:
						if(!usersEntity.checkFlag(values[i])) {
							check = "false";
						}
						break;
					case 4:
						if(!isValidDate(values[i])) {
							check = "false";
						}
						break;
					case 7:
						File file = new File(values[i]);
						if(values[i] == null) {
							check = "false";
						}else if(!file.exists()) {
							values[i] = URL;
						}
						break;
					default :
						if(values[i] == null) {
							check = "false";
						}
				}
				if(check.equals("false")) {
					break;
				}
				al.add(values[i]);
			}
			if(check.equals("true")) {
				usersEntity.bookInsert(al);	
			}
		} catch (SQLException | ClassNotFoundException e) {
			e.printStackTrace();
		}
		String book_style = values[3];
		try {
			if(usersEntity.enquryBookStyle(book_style)) {
				request.setAttribute("checkFlag", "T");
				request.setAttribute("book_style", book_style);
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		request.setAttribute("check", check);
		request.getRequestDispatcher("Main.jsp").forward(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
